package com.boil.qz.safekavass.shiro.realm;

import com.boil.qz.safekavass.model.LoginUser;
import com.boil.qz.safekavass.service.LoginUserService;
import com.boil.util.BaseController;
import com.boil.util.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;


/**
 * Created by ChenYong on 2017-05-03.
 * <br>
 * 用户授权认证。
 */
public class UserAuthRealm extends AuthorizingRealm {
    /**
     * 日志
     */
    private static Logger log = LoggerFactory.getLogger(BaseController.class);
    /**
     * 注入用户 Service
     */
    @Autowired
    private LoginUserService loginUserService;

    /**
     * 获取授权信息。
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("登录账号：{}--->进行授权", principalCollection.getPrimaryPrincipal());

        // 获取登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getSession().getAttribute(Constants.LOGIN_USER);

        // 获取用户的角色，暂无
        // no do...
        // 角色字符串 Set
        Set<String> roleSet = new HashSet<String>();
        // 权限字符串 Set
        Set<String> permSet = new HashSet<String>();
        // 简单授权信息
        SimpleAuthorizationInfo saInfo = new SimpleAuthorizationInfo();
        // 开始授权
        saInfo.addRoles(roleSet);
        saInfo.addStringPermissions(permSet);

        log.info("登录账号：{}--->拥有角色：{}，权限：{}", principalCollection.getPrimaryPrincipal(), saInfo.getRoles(), saInfo.getStringPermissions());

        return saInfo;
    }

    /**
     * 获取身份验证（登录验证）信息。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取登录令牌
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        // 获取账号
        String account = usernamePasswordToken.getUsername();
        // 查询登录用户
        LoginUser loginUser = loginUserService.findAdminByLoingid(account);

        log.info("登录账号：{}--->进行登录验证", account);

        // 简单身份验证信息
        SimpleAuthenticationInfo saInfo = null;

        // 登录账号找到
        if (loginUser != null) {
            saInfo = new SimpleAuthenticationInfo(account, loginUser.getPwd(), loginUser.getLoginName());
        }

        return saInfo;
    }
}